package com.example.security.event;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
@Async
public class ActiveEmailSender {

  private final RedisTemplate<String, Object> redisTemplate;

  public ActiveEmailSender(RedisTemplate<String, Object> redisTemplate) {
    this.redisTemplate = redisTemplate;
  }
  // 接收register事件, 并处理

  @EventListener
  public void sendActiveEmail(RegisterEvent registerEvent) throws NoSuchAlgorithmException {
    // 完善发送激活邮件, 以及用户点击邮件链接激活账户的业务流程

    var user = registerEvent.getUser();

    var email = user.getEmail();

    // 生成 Redis token MD5
    var userMd5 = DigestUtils.md5DigestAsHex(user.toString().getBytes());
    var ops = redisTemplate.boundValueOps(userMd5);
    ops.set(user.getId(), 30, TimeUnit.MINUTES);

    log.info("Redis active url: " + "http://localhost:8090/active/redis/" + userMd5);

    // 生成jwt的token
    var jwtToken =
        JWT.create()
            .withExpiresAt(new Date(System.currentTimeMillis() + 30 * 60 * 1000))
            .withSubject(user.getName())
            .withClaim("id", user.getId())
            .sign(Algorithm.HMAC512("ACTIVE-KEY"));

    log.info("Redis active url: " + "http://localhost:8090/active/" + jwtToken);
  }
}
